<script setup>
import { ref, onMounted, reactive, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '../../stores/user'
import axios from 'axios'

const userStore = useUserStore()
const isHR = computed(() => userStore.isHR)
const currentUserId = computed(() => userStore.userId)

const loading = ref(false)
const leaves = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('申请请假')
const isEdit = ref(false)
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const sortField = ref('createTime')
const sortOrder = ref('desc')

const formRef = ref(null)
const form = reactive({
  id: null,
  employeeId: '',
  employeeName: '',
  leaveType: 'PERSONAL',
  startDate: '',
  endDate: '',
  days: 0,
  reason: '',
  status: '待审批',
  approver: '',
  approveTime: '',
  approveRemark: ''
})

const rules = {
  employeeId: [{ required: true, message: '请选择员工', trigger: 'change' }],
  leaveType: [{ required: true, message: '请选择请假类型', trigger: 'change' }],
  startDate: [{ required: true, message: '请选择开始日期', trigger: 'change' }],
  endDate: [{ required: true, message: '请选择结束日期', trigger: 'change' }],
  days: [
    { required: true, message: '请输入请假天数', trigger: 'blur' },
    { type: 'number', message: '请假天数必须为数字', trigger: 'blur', transform: val => Number(val) }
  ],
  reason: [{ required: true, message: '请输入请假原因', trigger: 'blur' }]
}

const employees = ref([])
const leaveTypeOptions = [
  { value: 'PERSONAL', label: '事假' },
  { value: 'SICK', label: '病假' },
  { value: 'ANNUAL', label: '年假' },
  { value: 'MARRIAGE', label: '婚假' },
  { value: 'MATERNITY', label: '产假' },
  { value: 'FUNERAL', label: '丧假' }
]

const statusOptions = [
  { value: '待审批', label: '待审批', type: 'info' },
  { value: '已批准', label: '已批准', type: 'success' },
  { value: '已拒绝', label: '已拒绝', type: 'danger' }
]

// 过滤后的请假记录
const filteredLeaves = computed(() => {
  if (!searchQuery.value) return leaves.value
  
  const query = searchQuery.value.toLowerCase()
  return leaves.value.filter(leave => 
    (leave.employeeName && leave.employeeName.toLowerCase().includes(query)) || 
    (mapLeaveType(leave.leaveType).toLowerCase().includes(query)) ||
    (leave.startDate && leave.startDate.includes(query)) ||
    (leave.endDate && leave.endDate.includes(query)) ||
    (leave.status && leave.status.toLowerCase().includes(query)) ||
    (leave.reason && leave.reason.toLowerCase().includes(query)) ||
    (leave.approver && leave.approver.toLowerCase().includes(query))
  )
})

// 获取员工列表
const fetchEmployees = async () => {
  try {
    if (isHR.value) {
      const response = await axios.get('/users')
      employees.value = response.data
    } else {
      // 普通员工只加自己
      employees.value = [{
        id: userStore.userId,
        name: userStore.userInfo.name
      }]
    }
  } catch (error) {
    console.error('获取员工列表失败:', error)
    ElMessage.error('获取员工列表失败，请重试')
  }
}

// 获取请假记录（分页）
const fetchLeaves = async () => {
  try {
    loading.value = true
    let response
    if (isHR.value) {
      const params = {
        pageNum: currentPage.value,
        pageSize: pageSize.value,
        keyword: searchQuery.value,
        sortField: sortField.value,
        sortOrder: sortOrder.value
      }
      response = await axios.get('/leaves/page', { params })
      leaves.value = response.data.records.map(leave => ({
        id: leave.id,
        employeeId: leave.userId,
        employeeName: leave.userName,
        leaveType: leave.type,
        startDate: leave.startTime ? leave.startTime.split('T')[0] : '',
        endDate: leave.endTime ? leave.endTime.split('T')[0] : '',
        days: calculateDaysBetween(leave.startTime, leave.endTime),
        reason: leave.reason,
        status: mapStatus(leave.status),
        approver: leave.approverName || '',
        approveTime: leave.approveTime ? formatDateTime(leave.approveTime) : '',
        approveRemark: getApproveRemark(leave)
      }))
      total.value = response.data.total
    } else {
      response = await axios.get('/leaves/my')
      leaves.value = response.data.map(leave => ({
        id: leave.id,
        employeeId: leave.userId,
        employeeName: leave.userName,
        leaveType: leave.type,
        startDate: leave.startTime ? leave.startTime.split('T')[0] : '',
        endDate: leave.endTime ? leave.endTime.split('T')[0] : '',
        days: calculateDaysBetween(leave.startTime, leave.endTime),
        reason: leave.reason,
        status: mapStatus(leave.status),
        approver: leave.approverName || '',
        approveTime: leave.approveTime ? formatDateTime(leave.approveTime) : '',
        approveRemark: getApproveRemark(leave)
      }))
      total.value = response.data.length
    }
    loading.value = false
  } catch (error) {
    console.error('获取请假记录失败:', error)
    ElMessage.error('获取请假记录失败，请重试')
    loading.value = false
  }
}

// 计算两个日期之间的天数
const calculateDaysBetween = (startDate, endDate) => {
  if (!startDate || !endDate) return 0
  
  const start = new Date(startDate)
  const end = new Date(endDate)
  const diffTime = Math.abs(end - start)
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) + 1
  return diffDays
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  try {
    const date = new Date(dateTime)
    if (isNaN(date.getTime())) {
      return dateTime.replace('T', ' ').substring(0, 19)
    }
    // yyyy/M/d HH:mm:ss
    const y = date.getFullYear()
    const m = date.getMonth() + 1
    const d = date.getDate()
    const hh = String(date.getHours()).padStart(2, '0')
    const mm = String(date.getMinutes()).padStart(2, '0')
    const ss = String(date.getSeconds()).padStart(2, '0')
    return `${y}/${m}/${d} ${hh}:${mm}:${ss}`
  } catch (error) {
    return dateTime.replace('T', ' ').substring(0, 19)
  }
}

// 映射状态
const mapStatus = (status) => {
  const statusMap = {
    'PENDING': '待审批',
    'APPROVED': '已批准',
    'REJECTED': '已拒绝',
    'CANCELLED': '已取消'
  }
  return statusMap[status] || status
}

// 映射请假类型
const mapLeaveType = (type) => {
  const typeMap = {
    'PERSONAL': '事假',
    'SICK': '病假',
    'ANNUAL': '年假',
    'MARRIAGE': '婚假',
    'MATERNITY': '产假',
    'BEREAVEMENT': '丧假',
    'PATERNITY': '陪产假',
    'OTHER': '其他'
  }
  return typeMap[type] || type
}

// 获取审批意见
const getApproveRemark = (leave) => {
  if (leave.status === 'APPROVED') {
    return leave.approveReason || '同意请假'
  } else if (leave.status === 'REJECTED') {
    return leave.rejectReason || '拒绝请假'
  }
  return ''
}

// 打开添加请假记录对话框
const openAddDialog = () => {
  isEdit.value = false
  dialogTitle.value = '申请请假'
  form.id = null
  form.employeeId = currentUserId.value || ''
  form.employeeName = ''
  form.leaveType = 'PERSONAL'
  form.startDate = ''
  form.endDate = ''
  form.days = 0
  form.reason = ''
  form.status = '待审批'
  form.approver = ''
  form.approveTime = ''
  form.approveRemark = ''
  
  // 如果当前用户不是HR，自动填充自己的信息
  if (!isHR.value && currentUserId.value) {
    const currentEmployee = employees.value.find(e => e.id === currentUserId.value)
    if (currentEmployee) {
      form.employeeName = currentEmployee.name
    }
  }
  
  dialogVisible.value = true
}

// 打开编辑请假记录对话框
const openEditDialog = (row) => {
  isEdit.value = true
  dialogTitle.value = '编辑请假记录'
  form.id = row.id
  form.employeeId = row.employeeId
  form.employeeName = row.employeeName
  form.leaveType = row.leaveType
  form.startDate = row.startDate
  form.endDate = row.endDate
  form.days = row.days
  form.reason = row.reason
  form.status = row.status
  form.approver = row.approver
  form.approveTime = row.approveTime
  form.approveRemark = row.approveRemark
  dialogVisible.value = true
}

// 计算请假天数
const calculateDays = () => {
  if (form.startDate && form.endDate) {
    const start = new Date(form.startDate)
    const end = new Date(form.endDate)
    const diffTime = Math.abs(end - start)
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) + 1
    form.days = diffDays
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
        // 构造后端需要的请求体，只提交后端需要的字段
        const payload = {
          type: form.leaveType, // 直接使用英文枚举值
          startTime: form.startDate ? `${form.startDate}T00:00:00` : '',
          endTime: form.endDate ? `${form.endDate}T00:00:00` : '',
          reason: form.reason
        }
        
        console.log('提交的请假数据:', payload)
        
        // 使用Object.assign确保没有多余字段
        if (isEdit.value) {
          const response = await axios.put(`/leaves/${form.id}`, Object.assign({}, payload))
          ElMessage.success('请假记录更新成功')
        } else {
          const response = await axios.post('/leaves', Object.assign({}, payload))
          ElMessage.success('请假申请提交成功')
        }
        fetchLeaves()
        dialogVisible.value = false
      } catch (error) {
        console.error('提交请假记录失败:', error)
        if (error.response && error.response.data) {
          ElMessage.error(`提交失败: ${error.response.data.message || error.message}`)
        } else {
          ElMessage.error(`提同失败: ${error.message}`)
        }
      } finally {
        loading.value = false
      }
    }
  })
}

// 审批请假
const handleApprove = (row, approved) => {
  const action = approved ? '批准' : '拒绝'
  
  ElMessageBox.prompt(`确定要${action}此请假申请吗?`, '请输入审批意见', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPlaceholder: '请输入审批意见',
    inputValue: approved ? '同意请假' : '拒绝请假',
    inputPattern: /\S+/,
    inputErrorMessage: '审批意见不能为空',
    customClass: 'approve-dialog',
    roundButton: true,
    confirmButtonClass: approved ? 'el-button--success' : 'el-button--danger'
  }).then(async ({ value }) => {
    try {
      loading.value = true
      
      if (approved) {
        // 批准请假 - 添加审批意见参数
        await axios.put(`/leaves/${row.id}/approve?approveReason=${encodeURIComponent(value)}`)
      } else {
        // 拒绝请假
        await axios.put(`/leaves/${row.id}/reject?rejectReason=${encodeURIComponent(value)}`)
      }
      
      ElMessage.success(`请假申请已${action}`)
      // 重新获取请假记录
      fetchLeaves()
    } catch (error) {
      console.error('审批请假失败:', error)
      ElMessage.error('操作失败，请重试')
    } finally {
      loading.value = false
    }
  }).catch(() => {})
}

// 删除请假记录
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除此请假记录吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      loading.value = true
      await axios.delete(`/leaves/${row.id}`)
      ElMessage.success('请假记录删除成功')
      // 重新获取请假记录
      fetchLeaves()
    } catch (error) {
      console.error('删除请假记录失败:', error)
      if (error.response && error.response.data && error.response.data.message) {
        ElMessage.error(`删除失败: ${error.response.data.message}`)
      } else {
        ElMessage.error('删除失败，请重试')
      }
    } finally {
      loading.value = false
    }
  }).catch(() => {})
}

// 员工姓名变更处理
const handleEmployeeChange = (value) => {
  const employee = employees.value.find(e => e.id === Number(value))
  if (employee) {
    form.employeeName = employee.name
  }
}

// 获取状态标签类型
const getStatusType = (status) => {
  const option = statusOptions.find(item => item.value === status)
  return option ? option.type : ''
}

const handlePageChange = (page) => {
  currentPage.value = page
  fetchLeaves()
}
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchLeaves()
}
const handleSortChange = ({ prop, order }) => {
  if (prop && order) {
    sortField.value = prop
    sortOrder.value = order === 'ascending' ? 'asc' : 'desc'
  } else {
    sortField.value = 'createTime'
    sortOrder.value = 'desc'
  }
  currentPage.value = 1
  fetchLeaves()
}
const handleSearch = () => {
  currentPage.value = 1
  fetchLeaves()
}

onMounted(() => {
  fetchEmployees()
  fetchLeaves()
})
</script>

<template>
  <div class="leave-container">
    <div class="page-header">
      <div class="page-title">请假管理</div>
      <div class="header-actions">
        <!-- 添加搜索框 -->
        <el-input
          v-model="searchQuery"
          placeholder="搜索员工、请假类型、日期、状态或原因"
          clearable
          prefix-icon="el-icon-search"
          style="width: 300px; margin-right: 15px;"
          @change="handleSearch"
        />
        <el-button 
          type="primary" 
          @click="openAddDialog"
        >
          <el-icon><Plus /></el-icon>申请请假
        </el-button>
      </div>
    </div>
    
    <div class="table-container">
      <el-table 
        :data="leaves" 
        border 
        style="width: 100%" 
        v-loading="loading"
        @sort-change="handleSortChange"
        :default-sort="{ prop: 'createTime', order: 'descending' }"
      >
        <el-table-column prop="id" label="ID" width="60" />
        <el-table-column prop="employeeName" label="员工姓名" width="100" />
        <el-table-column prop="leaveType" label="请假类型" width="80">
          <template #default="{ row }">
            {{ mapLeaveType(row.leaveType) }}
          </template>
        </el-table-column>
        <el-table-column prop="startDate" label="开始日期" width="120" />
        <el-table-column prop="endDate" label="结束日期" width="120" />
        <el-table-column prop="days" label="天数" width="60" />
        <el-table-column prop="reason" label="请假原因" width="150" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="approver" label="审批人" width="100" />
        <el-table-column prop="approveRemark" label="审批意见" />
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <!-- HR管理员的操作 -->
            <template v-if="isHR">
              <!-- 待审批状态显示审批按钮 -->
              <div v-if="row.status === '待审批'" class="action-buttons">
                <el-button 
                  type="success" 
                  size="small" 
                  @click="handleApprove(row, true)"
                >
                  批准
                </el-button>
                <el-button 
                  type="danger" 
                  size="small" 
                  @click="handleApprove(row, false)"
                >
                  拒绝
                </el-button>
              </div>
              
              <!-- 所有状态都显示编辑和删除按钮 -->
              <div class="action-buttons">
                <el-button 
                  type="primary" 
                  size="small" 
                  @click="openEditDialog(row)"
                >
                  编辑
                </el-button>
                <el-button 
                  type="danger" 
                  size="small" 
                  @click="handleDelete(row)"
                >
                  删除
                </el-button>
              </div>
            </template>
            
            <!-- 普通员工的操作 -->
            <template v-else>
              <!-- 只有自己的记录可以编辑和删除 -->
              <div v-if="row.employeeId === currentUserId" class="action-buttons">
                <el-button 
                  type="primary" 
                  size="small" 
                  @click="openEditDialog(row)"
                  v-if="row.status === '待审批'"
                >
                  编辑
                </el-button>
                <el-button 
                  type="danger" 
                  size="small" 
                  @click="handleDelete(row)"
                >
                  撤回
                </el-button>
              </div>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>
    
    <!-- 添加/编辑请假记录对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="员工" prop="employeeId" v-if="isHR">
          <el-select 
            v-model="form.employeeId" 
            placeholder="请选择员工" 
            style="width: 100%"
            @change="handleEmployeeChange"
          >
            <el-option
              v-for="item in employees"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="请假类型" prop="leaveType">
          <el-select v-model="form.leaveType" placeholder="请选择请假类型" style="width: 100%">
            <el-option
              v-for="item in leaveTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker
            v-model="form.startDate"
            type="date"
            placeholder="选择开始日期"
            style="width: 100%"
            value-format="YYYY-MM-DD"
            @change="calculateDays"
          />
        </el-form-item>
        
        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker
            v-model="form.endDate"
            type="date"
            placeholder="选择结束日期"
            style="width: 100%"
            value-format="YYYY-MM-DD"
            @change="calculateDays"
          />
        </el-form-item>
        
        <el-form-item label="请假天数" prop="days">
          <el-input v-model="form.days" placeholder="请输入请假天数" type="number" />
        </el-form-item>
        
        <el-form-item label="请假原因" prop="reason">
          <el-input
            v-model="form.reason"
            type="textarea"
            rows="3"
            placeholder="请输入请假原因"
          />
        </el-form-item>
        
        <el-form-item label="状态" prop="status" v-if="isHR && isEdit">
          <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="审批意见" prop="approveRemark" v-if="isHR && isEdit">
          <el-input
            v-model="form.approveRemark"
            type="textarea"
            rows="2"
            placeholder="请输入审批意见"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.leave-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 20px 15px;
  background-color: #fff;
  border-bottom: 1px solid #ebeef5;
}

.page-title {
  font-size: 20px;
  font-weight: bold;
}

.table-container {
  flex: 1;
  padding: 0 20px 20px;
  background-color: #fff;
  overflow-y: auto;
}

/* 调整表格行高 */
:deep(.el-table__row) {
  height: 50px;
}

/* 调整表格头部样式 */
:deep(.el-table__header) {
  font-weight: bold;
  background-color: #f5f7fa;
}

/* 表格行悬停效果 */
:deep(.el-table__row:hover) {
  background-color: #f0f8ff !important;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  gap: 8px;
  margin-bottom: 8px;
}

.action-buttons:last-child {
  margin-bottom: 0;
}
</style> 